package gggameserver.games.connection;

import gggameserver.exceptions.GGTimeout;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class GGSocketConnection implements GGConnection {

	private Socket socket;
	private PrintWriter out;
	private BufferedReader in;

	public GGSocketConnection(Socket socket) throws IOException {
		this.socket = socket;
		this.out = new PrintWriter(this.socket.getOutputStream(), false);
		this.in = new BufferedReader(new InputStreamReader(
				this.socket.getInputStream()));
	}

	public void sendCommand(String cmd) {
		synchronized (this.out) {
			System.out.println(this + ">" + cmd); // TODO
			this.out.print(cmd);
			this.out.print('\n');
			this.out.flush();
		}
		;
	}

	public String receiveCommand(long timeout) throws GGTimeout {
		// TODO Auto-generated method stub timeout not implemented
		synchronized (this.in) {
			String line = null;
			try {
				line = this.in.readLine();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(this + "<" + line); // TODO
			return line;
		}
	}

	public void close() {
		try {
			this.socket.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
